package cn.hy.preparelesson.module.business;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hy.preparelesson.common.entity.PlLesson;
import cn.hy.preparelesson.common.entity.PlPostscript;
import cn.hy.preparelesson.common.enums.SchoolSemesterEnum;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.params.PageParams;
import cn.hy.preparelesson.common.permission.RequirePermissions;
import cn.hy.preparelesson.common.service.PlLessonService;
import cn.hy.preparelesson.common.service.PlPostScriptService;
import cn.hy.preparelesson.common.utils.HttpUtils;
import cn.hy.preparelesson.common.utils.UserUtils;
import cn.hy.preparelesson.common.utils.ValidatorUtils;
import cn.hy.preparelesson.common.vo.PageInfo;
import cn.hy.preparelesson.common.vo.PlPostscriptListVo;
import cn.hy.preparelesson.common.vo.Result;
import cn.hy.preparelesson.module.business.vo.PersonPostscriptExportVo;
import cn.hy.preparelesson.module.business.vo.SchoolLessonExportVo;
import cn.hy.preparelesson.module.business.vo.SchoolPostscriptExportVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 后记管理 Controller
 */

@RequestMapping("/postscript")
@RestController
public class PLPostScriptController {

    @Autowired
    private PlPostScriptService plPostScriptService;

    @Autowired
    private PlLessonService plLessonService;

    /**
     * 分页获取后记数据
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param createEndTime
     * @param subjectId
     * @param term
     * @param schoolYear
     * @param distanceYear
     * @param classId
     * @return
     */
    @RequirePermissions("pl:personpostscript:list")
    @RequestMapping("/list")
    public  Result findPageBy(@RequestParam("schoolToken")String schoolId, PageParams pageParams, String title, Date createStartTime, Date createEndTime, String subjectId,
                              Byte term, Integer schoolYear,  BigDecimal distanceYear,  String classId) throws TException {
        PageInfo<PlPostscript> pageInfo =  plPostScriptService.findPlPostscriptValidPageBy(schoolId, pageParams, title, createStartTime, createEndTime, subjectId, term, schoolYear, distanceYear, classId, UserUtils.getUserId());
        return Result.success(pageInfo);
    }

    /**
     * 分页获取全校后记数据
     * @param schoolId
     * @param pageParams
     * @param title
     * @param createStartTime
     * @param createEndTime
     * @param subjectId
     * @param term
     * @param schoolYear
     * @param distanceYear
     * @param classId
     * @return
     */
    @RequirePermissions("pl:schoolpostscript:list")
    @RequestMapping("/schoolList")
    public  Result findSchoolPostscriptPageBy(@RequestParam("schoolToken")String schoolId, PageParams pageParams, String title, Date createStartTime, Date createEndTime, String subjectId,
                              Byte term, Integer schoolYear,  BigDecimal distanceYear,  String classId) throws TException {
        PageInfo<PlPostscript> pageInfo =  plPostScriptService.findPlPostscriptValidPageBy(schoolId, pageParams, title, createStartTime, createEndTime, subjectId, term, schoolYear, distanceYear, classId, null);
        return Result.success(pageInfo);
    }

    /**
     * 保存/编辑
     * @param schoolId
     * @param plPostscript
     * @return
     */
    @RequirePermissions("pl:personpostscript:addOrEdit")
    @RequestMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestParam("schoolToken")String schoolId, PlPostscript plPostscript){
        ValidatorUtils.validateEntity(plPostscript);
        PlLesson checkPlLesson = plLessonService.findValidPlLessonByIdAndCreateBy(schoolId, plPostscript.getLessonId(), UserUtils.getUserId());
        if (checkPlLesson == null) {
            throw new MessageException("当前备课不存在或者已被删除");
        }
        if(!UserUtils.getUserId().equals(checkPlLesson.getCreateBy())) {
            throw new MessageException("您只能添加或编辑个人备课的后记!");
        }

        if (StringUtils.isNotBlank(plPostscript.getId())) {
            plPostScriptService.update(schoolId, UserUtils.getUserId(), plPostscript);
        } else {
            PlPostscript checkPostScript = plPostScriptService.findVaildPostScriptBySchoolIdAndLessonId(schoolId, plPostscript.getLessonId());
            if (checkPostScript != null) {
                throw new MessageException("当前备课已存在后记!");
            }
            plPostScriptService.save(schoolId, UserUtils.getUserId(), plPostscript);
        }

        return Result.success(null);
    }

    /**
     * 获取后记详情
     * @param schoolId
     * @param lessonId
     * @param postscriptId
     * @return
     */
    @RequestMapping("/detail")
    public Result getDetail(@RequestParam("schoolToken") String schoolId, @RequestParam String lessonId, String postscriptId) {
        PlPostscript plPostscript = plPostScriptService.findValidPostscriptDetailBy(schoolId, lessonId, postscriptId);
        return Result.success(plPostscript);
    }

    /**
     * 删除后记
     * @param schoolId
     * @param postscriptId
     * @param lessonId
     * @return
     */
    @RequirePermissions("pl:personpostscript:delete")
    @RequestMapping("/delete")
    public Result delete(@RequestParam("schoolToken")String schoolId, @RequestParam String postscriptId, @RequestParam String lessonId) {
        plPostScriptService.softDelete(schoolId, postscriptId, lessonId);
        return Result.success(null);
    }

    /***
     * 导出个人后记信息
     * @param request
     * @param response
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param createEndTime
     * @param subjectId
     * @param term
     * @param schoolYear
     * @param distanceYear
     * @param classId
     * @throws TException
     */
    @RequirePermissions("pl:personpostscript:export")
    @RequestMapping("/exportPerson")
    public void exportPersonPostscript(HttpServletRequest request, HttpServletResponse response,@RequestParam("schoolToken")String schoolId, String title, Date createStartTime, Date createEndTime, String subjectId,
                                       Byte term, Integer schoolYear,  BigDecimal distanceYear,  String classId) throws TException {
        PageParams pageParams = new PageParams();
        pageParams.setPageSize(Integer.MAX_VALUE);
        PageInfo<PlPostscriptListVo> pageInfo =  plPostScriptService.findValidBy(schoolId, pageParams, title, createStartTime, createEndTime, subjectId, term, schoolYear, distanceYear, classId, UserUtils.getUserId());
        List<PersonPostscriptExportVo> exportVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(pageInfo.getList())) {
            int seq = 1;
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            for (PlPostscriptListVo postscript : pageInfo.getList()) {
                PersonPostscriptExportVo exportVo = new PersonPostscriptExportVo();
                exportVo.setSeq(seq ++);
                if (postscript.getSchoolYear() != null && postscript.getTerm() != null){
                    String currentTerm = postscript.getTerm().equals(SchoolSemesterEnum.ONE.getCode()) ? "一" : "二";
                    int year = postscript.getSchoolYear()+1;
                    exportVo.setSemester(postscript.getSchoolYear() + "年-" + year + "第" + currentTerm + "学期");
                }
                exportVo.setTitle(postscript.getTitle());
                exportVo.setAssociatedLessons(postscript.getLessonTitle());
                if (StringUtils.isNotBlank(postscript.getGradeName())) {
                    exportVo.setGrade(postscript.getGradeName());
                }
                if (StringUtils.isNotBlank(postscript.getClassNameStr())) {
                    List<String> classNameList = new ArrayList<>();
                    for (String tempClassName : postscript.getClassNameStr().split(",") ) {
                        classNameList.add(tempClassName + "班");
                    }
                    exportVo.setClassName(String.join(",", classNameList));
                }
                if (StringUtils.isNotBlank(postscript.getSubjectName())) {
                    exportVo.setSubjectName(postscript.getSubjectName());
                }
                exportVo.setCreateBy(postscript.getCreateName());
                exportVo.setCreateAt(dateFormat.format(postscript.getCreateAt()));
                exportVoList.add(exportVo);
            }
            Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(null, null, ExcelType.XSSF),
                    PersonPostscriptExportVo.class, exportVoList);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + HttpUtils.getEncodeFileName(request, "我的后记.xlsx"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                sheets.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导出全校后记
     * @param request
     * @param response
     * @param schoolId
     * @param title
     * @param createStartTime
     * @param createEndTime
     * @param subjectId
     * @param term
     * @param schoolYear
     * @param distanceYear
     * @param classId
     * @throws TException
     */
    @RequirePermissions("pl:schoolpostscript:export")
    @RequestMapping("/exportSchool")
    public void exportSchoolPostscript(HttpServletRequest request, HttpServletResponse response,@RequestParam("schoolToken")String schoolId, String title, Date createStartTime, Date createEndTime, String subjectId,
                                       Byte term, Integer schoolYear,  BigDecimal distanceYear,  String classId) throws TException {
        PageParams pageParams = new PageParams();
        pageParams.setPageSize(Integer.MAX_VALUE);
        PageInfo<PlPostscriptListVo> pageInfo =  plPostScriptService.findValidBy(schoolId, pageParams, title, createStartTime, createEndTime, subjectId, term, schoolYear, distanceYear, classId, null);
        List<SchoolPostscriptExportVo> exportVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(pageInfo.getList())) {
            int seq = 1;
            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            for (PlPostscriptListVo postscript : pageInfo.getList()) {
                SchoolPostscriptExportVo exportVo = new SchoolPostscriptExportVo();
                exportVo.setSeq(seq ++);
                if (postscript.getSchoolYear() != null && postscript.getTerm() != null){
                    String currentTerm = postscript.getTerm().equals(SchoolSemesterEnum.ONE.getCode()) ? "一" : "二";
                    int year = postscript.getSchoolYear()+1;
                    exportVo.setSemester(postscript.getSchoolYear() + "年-" + year + "第" + currentTerm + "学期");
                }
                exportVo.setTitle(postscript.getTitle());
                exportVo.setAssociatedLessons(postscript.getLessonTitle());
                if (StringUtils.isNotBlank(postscript.getGradeName())) {
                    exportVo.setGrade(postscript.getGradeName());
                }
                if (StringUtils.isNotBlank(postscript.getClassNameStr())) {
                    List<String> classNameList = new ArrayList<>();
                    for (String tempClassName : postscript.getClassNameStr().split(",") ) {
                        classNameList.add(tempClassName + "班");
                    }
                    exportVo.setClassName(String.join(",", classNameList));
                }
                if (StringUtils.isNotBlank(postscript.getSubjectName())) {
                    exportVo.setSubjectName(postscript.getSubjectName());
                }
                exportVo.setCreateBy(postscript.getCreateName());
                exportVo.setCreateAt(dateFormat.format(postscript.getCreateAt()));
                exportVoList.add(exportVo);
            }
            Workbook sheets = ExcelExportUtil.exportExcel(new ExportParams(null, null, ExcelType.XSSF),
                    SchoolPostscriptExportVo.class, exportVoList);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + HttpUtils.getEncodeFileName(request, "全校后记.xlsx"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                sheets.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
